package middleware

import (
	"net"
	"net/http"
	"os"
	"runtime/debug"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// GinLogger Gin logging middleware
func (m *Middleware) GinLoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Skip logging for static files
		if isStaticFile(c.Request.URL.Path) {
			c.Next()
			return
		}

		// Record start time
		start := time.Now()

		c.Next()

		// Calculate execution time
		duration := time.Since(start)

		m.Logger.Info("request completed",
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", c.Request.URL.Path),
			zap.Duration("duration", duration),
		)
	}
}

// isStaticFile checks if the request path is for a static file
func isStaticFile(path string) bool {
	// Common static file extensions
	staticExtensions := []string{
		".css", ".js", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico",
		".woff", ".woff2", ".ttf", ".eot", ".map", ".txt", ".xml", ".json",
		".pdf", ".zip", ".tar", ".gz",
	}

	// Check file extension
	for _, ext := range staticExtensions {
		if strings.HasSuffix(strings.ToLower(path), ext) {
			return true
		}
	}

	// Common static file paths
	staticPaths := []string{
		"/static/", "/assets/", "/uploads/", "/resources/", "/favicon.ico",
	}

	// Check path prefixes
	for _, prefix := range staticPaths {
		if strings.HasPrefix(path, prefix) {
			return true
		}
	}

	return false
}

// GinRecovery returns a middleware that recovers panics using custom zap.Logger
// stack parameter determines whether to output stack trace in logs
func (m *Middleware) GinRecoveryMiddleware(stack bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// Check if it's a broken connection, no need to log stack trace
				var brokenPipe bool
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				// If connection is broken, cannot write status code, log error and abort context
				if brokenPipe {
					m.Logger.Error(c.Request.URL.Path,
						zap.Any("error", err),
					)
					c.Error(err.(error))
					c.Abort()
					return
				}

				// Log stack information based on configuration
				if stack {
					m.Logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("method", c.Request.Method),
						zap.String("path", c.Request.URL.Path),
						zap.String("query", c.Request.URL.RawQuery),
						zap.String("ip", c.ClientIP()),
						zap.String("user-agent", c.Request.UserAgent()),
						zap.String("stack", string(debug.Stack())),
					)
				} else {
					m.Logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("method", c.Request.Method),
						zap.String("path", c.Request.URL.Path),
						zap.String("query", c.Request.URL.RawQuery),
						zap.String("ip", c.ClientIP()),
						zap.String("user-agent", c.Request.UserAgent()),
					)
				}
				// Return 500 status code
				c.AbortWithStatus(http.StatusInternalServerError)
			}
		}()
		c.Next()
	}
}
